package com.fanghuaman.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fanghuaman.auth.mapper.UserMapper;
import com.fanghuaman.auth.service.AuthService;
import com.fanghuaman.model.auth.dto.AuthParamsDto;
import com.fanghuaman.model.auth.pojo.UserExt;
import com.fanghuaman.model.common.vo.ResponseResult;
import com.fanghuaman.model.user.dto.LoginDto;
import com.fanghuaman.model.user.pojo.User;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 自定义认证类
 * </p>
 *
 * @author smh
 * @since 2024-11-24
 */
@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {
    private static final String AUTHSERVICE = "AuthService";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 获取UserDetails
     *
     * @param userExt
     * @return
     */
    private static UserDetails getUserDetails(UserExt userExt) {
        //为了安全,不放密码
        String password = userExt.getPassword();
        userExt.setPassword(null);
        String userString = JSON.toJSONString(userExt);

        // 返回用户信息
        String[] authorities = {"test"};
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(userString) // 用户名
                .password(password) // 用户密码
                .authorities(authorities) // 用户权限
                .build();
        return userDetails;
    }

    /**
     * 根据用户名查询用户信息(比对密码的过程没在这里,但是因为后面屏蔽了密码校验,所以自定义密码校验在这里)
     *
     * @param s 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //这里可以让s是一个json串,来设置不同的登录方式
        AuthParamsDto authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        if (authParamsDto == null) {
            log.info("认证请求格式不对");
            throw new RuntimeException("认证请求数据格式不对");
        }

        // 判断用哪种方式校验
        String authType = authParamsDto.getAuthType();
        // 根据bean名获取bean
        AuthService authService = applicationContext.getBean(authType + "_" + AUTHSERVICE, AuthService.class);
        // 调用认证方法
        UserExt userExt = authService.auth(authParamsDto);

        // 获取UserDetails
        UserDetails userDetails = getUserDetails(userExt);

        return userDetails;

    }
}
